package cn.jofei.common.thread;

import cn.jofei.common.config.AppProperties;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.DefaultThreadFactory;

import java.util.concurrent.*;

/**
 * 公用线程池
 *
 * @author Jofei Bao
 * @version ngbao v2.0
 * @date 2022年05月22日 16:37
 */
public abstract class CommonEventLoop {

    public static final NioEventLoopGroup BOSS_GROUP = new NioEventLoopGroup(
            AppProperties.get("server.group.boss-size", Integer.class).orElse(2),
            new DefaultThreadFactory("boss", false));

    public static final NioEventLoopGroup WORK_GROUP = new NioEventLoopGroup(
            AppProperties.get("server.group.worker-size", Integer.class).orElse(4),
            new DefaultThreadFactory("worker", false));

    public static void scheduled(ScheduledJob task, Integer period) {
        task.future = WORK_GROUP.scheduleAtFixedRate(task, 0, period, TimeUnit.SECONDS);
    }

    public static ThreadInfo info() {
        ThreadInfo threadInfo = new ThreadInfo();
        threadInfo.setCorePoolSize(CommonEventLoop.WORK_GROUP.executorCount());
        threadInfo.setPoolSize(CommonEventLoop.WORK_GROUP.spliterator().characteristics());
        threadInfo.setQueueSize(CommonEventLoop.WORK_GROUP.spliterator().getExactSizeIfKnown());
        return threadInfo;
    }
}
